package com.zy.ems.common.util;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.zy.ems.common.http.HttpClientUtil;

/**
 * 文件上传工具类。
 * 
 * @author Luffy
 *
 */
public class FileUploadUtil {
	private static Logger logger = Logger.getLogger(FileUploadUtil.class);

	/**
	 * 文件上传属性文件名
	 */
	private static final String FILEUPLOAD_PROPERTIES_FILE_NAME = "fileuplaod";

	/**
	 * 图片服务器地址属性名
	 */
	private final static String IMAGE_SERVER_URL_NAME = "imageServerUrl";

	/**
	 * 图片上传地址属性名
	 */
	private final static String IMAGE_UPLOAD_URL_NAME = "imageUpServerUrl";

	/**
	 * 图片上传字段属性名
	 */
	private final static String IMAGE_FIELD_NAME = "imageFieldName";

	/**
	 * 文件上传临时目录
	 */
	private static final String VIRTUAL_PATH = "/tempUpload";

	/**
	 * 图片服务器地址
	 */
	private static String imageServerUrl;

	/**
	 * 图片上传服务地址
	 */
	private static String imageUpServerUrl;

	/**
	 * 上传图片字段名称
	 */
	private static String imageFieldName;

	static {
		ResourceBundle rb = ResourceBundle.getBundle(FILEUPLOAD_PROPERTIES_FILE_NAME);
		imageServerUrl = rb.getString(IMAGE_SERVER_URL_NAME);
		imageUpServerUrl = rb.getString(IMAGE_UPLOAD_URL_NAME);
		imageFieldName = rb.getString(IMAGE_FIELD_NAME);
	}

	/**
	 * 获取图片服务器地址，最后以“/”结尾。
	 * 
	 * @return
	 */
	public static String getImageServer() {
		Assert.notNull(imageServerUrl, "图片服务器地址不能为空");
		String uri = URI.create(imageServerUrl).toString();
		if (!uri.endsWith("/")) {
			uri = uri + "/";
		}
		return uri;
	}

	/**
	 * 图片上传。
	 * 
	 * @param request
	 * @return
	 */
	public static List<String> uploadImages(HttpServletRequest request) {
		MultipartHttpServletRequest mRequest = null;
		if (request instanceof MultipartHttpServletRequest) {
			mRequest = (MultipartHttpServletRequest) request;
		} else {
			throw new IllegalArgumentException("不支持的请求类型！");
		}
		// 图片上传临时目录
		String dirPath = request.getSession().getServletContext().getRealPath(VIRTUAL_PATH) + File.separator;
		if (!new File(dirPath).exists()) {
			new File(dirPath).mkdirs();
		}

		List<String> resultList = new ArrayList<String>();
		for (Iterator<String> it = mRequest.getFileNames(); it.hasNext();) {
			List<MultipartFile> mFiles = mRequest.getFiles(it.next());
			for (MultipartFile mfile : mFiles) {
				if (mfile.getName().length() <= 0 || mfile.getSize() <= 0) {
					continue;
				}
				File tempUploadFile = new File(dirPath, mfile.getOriginalFilename());
				try {
					mfile.transferTo(tempUploadFile);
				} catch (IllegalStateException e) {
					logger.error(e.getMessage(), e);
				} catch (IOException e) {
					logger.error(e.getMessage(), e);
				}
				// 图片上传
				String result = HttpClientUtil.uploadFile(imageUpServerUrl, imageFieldName,
						tempUploadFile.getAbsolutePath(), null, mfile.getContentType());
				resultList.add(result);
				if (!tempUploadFile.delete()) {
					tempUploadFile.deleteOnExit();
				}
			}
		}
		return resultList;
	}

}
